<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :checkedit="checkedit" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal, ptFloat, minusF } from '@/static/js/common.js';
import { buildFormData, formValidation, tranferToEditors, changeEditor,setSubmitSubValue, configSelectData, hasValue,formShowLoading ,getFormFields,formModelLoad,getWorkCacheKey} from '@/static/js/formUtil.js';
import urlUtil from '@/static/js/urlUtil.js';
import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
import moment from '@/static/js/moment.js'
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			formdata: {
				paySum:""
			},
			initValue: {
				zuserId:"",
				zuserName:"",
				zinstId:"",
				zinstName:"",
				paySum:"",
				dataStr:"",
			},
			payeeNameCacheKey:"fin-pay-applys-payeename-cache",
			currencyIdCacheKey:'fin-pay-applys-currency-cache',
			userCacheKey:'fin-pay-applys-user-cache'
		})
	},
	computed: { 
		...mapState(useLoginUserStore, ['userName', 'userId','salaryInstId','salaryInstName'])
	},
	methods: {
		onInputPayeeBankNum(val){
			let _that = this
			let reg =/[\u4e00-\u9fa5]/g;
			_that.$refs.autoform.formdata.payeeBankNum = val.replace(reg, "")
		},
		clearPaySum(){
			let _that = this
			let flag = false
			if(_that.subEditorObj["title2"]){
				if(_that.subEditorObj["title2"].workList.length > 0){
					for(let item of _that.subEditorObj["title2"].workList){
						if(item.payNum){
							flag = true
						}
					}
				}else{
					_that.$refs.autoform.clear("title1","paySum")
				}
				
			}
			if(flag){
				let title = _that.$refs.autoform.getEditorTitle("title1","paySum")
				confirmModal(_that,'提示信息',"修改“"+title+"”将会清空付款明细，是否继续？",()=>{
					_that.subEditorObj["title2"].workList = []
					_that.$refs.autoform.clear("title1","paySum")
				},()=>{})
			}
		},
		onInputPaySum(){
			let _that = this
			let flag = false
			if(_that.subEditorObj["title2"]){
				for(let item of _that.subEditorObj["title2"].workList){
					if(item.payNum){
						flag = true
					}
				}
			}
			if(flag){
				let title = _that.$refs.autoform.getEditorTitle("title1","paySum")
				confirmModal(_that,'提示信息',"修改“"+title+"”将会清空付款明细，是否继续？",()=>{
					_that.subEditorObj["title2"].workList = []
					_that.$refs.autoform.clear("title1","paySum")
				},()=>{})
			}
		},
		clearPayeeName(){
			let _that = this
			_that.$refs.autoform.clear("title1","payeeName")
			_that.$refs.autoform.clear("title1","payeeBankName")
			_that.$refs.autoform.clear("title1","payeeBankNum")
		},
		onSubChange(){
			let _that = this.$refs.autoform
			if(this.subEditorObj["title2"].workList.length) {
				_that.formdata.paySum = this._.sum(this.subEditorObj["title2"].workList.map(e=>ptFloat(e.payNum)))
			} else {
				_that.formdata.paySum = 0
			}
			this.getCapitalPaySum()
		},
		getCapitalPaySum() {
			let _that = this;
			if(_that.$refs.autoform.formdata.paySum){
				_that.om.request("common/getCapitalNum", {
					moneyNum: _that.$refs.autoform.formdata.paySum
				}).then(res => {
					if (res.succeed) {
						_that.$refs.autoform.formdata.capitalPaySum = res.value
					}
				})
			}else{
				_that.$refs.autoform.formdata.capitalPaySum = ""
			}
		},
		formSubmit() {
			let _that = this;
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				//子表提交数据赋值
				setSubmitSubValue()
				if (!_that.formdata.dataStr) {
					this.om.toast('请配置' + this.subEditorObj['title2'].title);
					return;
				}
				if(this.checkedit) {
					_that.om.formSave('commonForm/doCheckOrApproveUpdate', _that.formdata, _that)
				}else if(_that.edit){
					_that.om.formSave('payApplicationForm/doUpdate', _that.formdata, _that)
				} else {
					_that.om.formSave('payApplicationForm/doAdd', _that.formdata, _that)
				}
			}
		},
		getWorkParam() {
			return {
				checkedit:(this.checkedit?true:""),
				userId:this.userId,
				userName:this.userName,
				posId:this.formdata.zposId,
				posName:this.formdata.zposName,
				instId:this.formdata.zinstId,
				instName:this.formdata.zinstName
			}
		},
		onSelectZpos(item){
			this.$refs.autoform.formdata.zinstId = item.instId
			this.$refs.autoform.formdata.zinstName = item.instName
		},
		onSelectPayType(item) {
			let _that = this;
			if(item.id == "5845"){
				_that.$refs.autoform.changeEditor("title1","payeeName","required",true)
				_that.$refs.autoform.changeEditor("title1","payeeBankName","required",true)
				_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",true)
				
			}else{
				_that.$refs.autoform.changeEditor("title1","payeeName","required",false)
				_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
				_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",false)
			}	
		},
		clearPayType(){
			let _that = this;
			_that.$refs.autoform.clear("title1","payTypeId")
			_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankNum","required",false)
		},
		onSelectPayeeName(data){
			if(Object.prototype.toString.call(data) == "[object Object]"){
				if(this.$refs.autoform.formdata.payTypeId  == '5845'){
					this.$refs.autoform.formdata.payeeName = data.payeeName
					this.$refs.autoform.formdata.payeeBankName = data.payeeBankName
					this.$refs.autoform.formdata.payeeBankNum = data.payeeBankNum
				}else{
					this.$refs.autoform.formdata.payeeName = data.payeeName
					this.$refs.autoform.formdata.payeeBankName = ''
					this.$refs.autoform.formdata.payeeBankNum = ''
				}
			}else{
				this.$refs.autoform.formdata.payeeName = data
				this.$refs.autoform.formdata.payeeBankName = ''
				this.$refs.autoform.formdata.payeeBankNum = ''
			}
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code),
				urlUtil.dictZeroComboboxUrl('37846'),
				{
					url:'currencyDict/getLocalCurrency',
				},
				{
					url:'dictSource/loadCombo',
					param:{
						sourceId:'289',
						categoryId: '6761'
					}
				} 
			];
			var fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:"payApplicationForm/getValue",
					param:{fileId:fileId}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posname'), mainData);
				changeEditor('title1', 'payTypeId', 'data', configSelectData(res[1], 'id', 'dicname'), mainData);
				changeEditor('title1', 'useRemarkId', 'data', configSelectData(res[3], 'id', 'text'), mainData);
				changeEditor("title1","currencyId",{
					link:'../../public/pageSearch/pageSearch',
					"linkParam":{
						namefield:'currencyCode',
						notefield:'currencyName',
						initload:true,
						searchfield:'q',
						pagination:true,
						cachename:_that.currencyIdCacheKey,
						url:'currencyDict/getCurrency',
						method:'get'
					}
				},null,mainData)
				changeEditor('title1', 'payeeName', "linkParam", {
					namefield:"payeeName",
					initload:true,
					url:"payApplicationFormShow/likeSerchPayeeName",
					cachename:_that.payeeNameCacheKey,
					searchfield:'q',
					pagination:true,
					selectTitle:"收款方"
				}, mainData);
				changeEditor("title2", "dataStr", {
					getWorkParam: 'getWorkParam',
					titleTemplate:" ¥ <%= payNum || '无'%>",
					subtitle1Template:"<%= remark || '无'%>"
				}, null, mainData)
				changeEditor("title1","applyPayDate",{
					defaultValue:moment().format('YYYY-MM-DD'),
					defaultName:moment().format('YYYY-MM-DD')
				},null,mainData)
				changeEditor("title1","userId",{
					defaultValue:_that.userId,
					defaultName:_that.userName
				},null,mainData)
				changeEditor("title1","instId",{
					defaultValue:_that.salaryInstId,
					defaultName:_that.salaryInstName
				},null,mainData)
				changeEditor("title1","userId", {
					'link':'../../public/searchUser/searchUser',
					linkParam: {
						cachename: _that.userCacheKey,
						isNew:true,
						isUserPos:true,
						isSingle:true,
						placeholder: urlUtil.userPageUrl().prompt,
						pagination: true
					}
				}, null, mainData);
				//审核修改
				if(fileId) {
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id")
					fieldArr.push("dataStr")
					var dataList = _that._.cloneDeep(res[4].value.dataList)
					_that.subEditorObj["title2"].workList = dataList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "dataStr", JSON.stringify(dataList))
					_that.$set(_that.formdata, "dataStr", JSON.stringify(dataList))
					delete res[4].value.dataList
					for(var i in res[4].value){
						if(fieldArr.includes(i)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[4].value[i])
							_that.$set(_that.formdata, i, res[4].value[i])
						}
					}
					if(_that.formdata.payTypeId == "5845"){
						changeEditor("title1","payeeName","required",true,mainData)
						changeEditor("title1","payeeBankName","required",true,mainData)
						changeEditor("title1","payeeBankNum","required",true,mainData)
						
					}else{
						changeEditor("title1","payeeName","required",false,mainData)
						changeEditor("title1","payeeBankName","required",false,mainData)
						changeEditor("title1","payeeBankNum","required",false,mainData)
					}	
					if(_that.subEditorObj["title2"]){
						changeEditor("title2", "dataStr", {
							showDel: !_that.checkedit,
							showAdd:!_that.checkedit
						}, null, mainData)
					}
					//修改时初始化下拉框的值
					_that.$nextTick(function(){
						if(_that.$refs.autoform){
							_that.$refs.autoform.initSelectIndex('topinfo', 'zposId')
							_that.$refs.autoform.initSelectIndex('title1', 'payTypeId')
							_that.$refs.autoform.initSelectIndex('title1', 'useRemarkId')
						}
					})
				}else{
					//初始化下拉框的值
					_that.$nextTick(function(){
						this.$nextTick(function(){
							if(this.$refs.autoform){
								if(res[0].length == 1) {
									this.$refs.autoform.initSelectIndex('topinfo', 'zposId', res[0][0].id)
									this.onSelectZpos(res[0][0])
								}
								if(!this.$refs.autoform.formdata.currencyId){
									this.$refs.autoform.formdata.currencyId = res[2].value.id
									this.$refs.autoform.formdata.currencyStr = res[2].value.codeNameUnit
								}
							}
						})
						if(!_that.$refs.autoform.formdata.zposId){
							_that.$refs.autoform.initSelectVal("topinfo","zposId")
						}
					})
				}
			}, options)
		},
	},
	onLoad(options) {
		this.initLoad(options);
	},
	onUnload(){
		//#ifdef APP-PLUS
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				uni.removeStorage({
					key: getWorkCacheKey(fieldId)
				});
			}
		}
		//#endif
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				let editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						_that.onSubChange(editor)
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key:_that.userCacheKey,
				success:(res)=>{
					if(res.data){
						let d = res.data[0]
						let formdata = _that.$refs.autoform.formdata
						formdata.userId = d.id
						formdata.userName = d.username
						formdata.instId = d.instId
						formdata.instName = d.instName
						uni.removeStorage({
							key:_that.userCacheKey
						})
					}
				}
			})
			uni.getStorage({
				key: this.payeeNameCacheKey,
				success: function(res) {
					if(res.data) {
						let d = res.data
						_that.onSelectPayeeName(d)
						uni.removeStorage({
							key: _that.payeeNameCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key:_that.currencyIdCacheKey,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.currencyId = d.id
						formdata.currencyStr = d.codeNameUnit
						uni.removeStorage({
							key:_that.currencyIdCacheKey
						})
					}
				} 
			})
		}
	}
};
</script>
<style></style>
